/// <reference types="chrome"/>

interface SubtitleMessage {
  type: 'SUBTITLE_UPDATE';
  subtitle: string;
}

interface FetchSubtitleRequest {
  type: 'FETCH_SUBTITLE';
  url: string;
}

interface FetchSubtitleResponse {
  success: boolean;
  data?: any;
  error?: string;
}

type MessageType = SubtitleMessage | FetchSubtitleRequest;
type SubtitleResponseType = FetchSubtitleResponse;

// 存储环境变量键名
const STORAGE_ENV = 'bilibili-subtitle-env';

// 后台服务脚本

interface SubtitleData {
  text: string;
  timestamp: number;
  videoTime: number;
}

interface StorageData {
  subtitles: SubtitleData[];
  maxSubtitles: number;
}

class SubtitleManager {
  private static readonly MAX_SUBTITLES = 1000; // 最大存储字幕数量
  private static readonly STORAGE_KEY = 'subtitles';

  constructor() {
    this.init();
  }

  private async init() {
    // 初始化存储
    const data = await this.getStorageData();
    if (!data.subtitles) {
      await this.setStorageData({
        subtitles: [],
        maxSubtitles: SubtitleManager.MAX_SUBTITLES
      });
    }
  }

  private async getStorageData(): Promise<StorageData> {
    return new Promise((resolve) => {
      chrome.storage.local.get(['subtitles', 'maxSubtitles'], (result) => {
        resolve({
          subtitles: result.subtitles || [],
          maxSubtitles: result.maxSubtitles || SubtitleManager.MAX_SUBTITLES
        });
      });
    });
  }

  private async setStorageData(data: StorageData): Promise<void> {
    return new Promise((resolve) => {
      chrome.storage.local.set(data, resolve);
    });
  }

  public async addSubtitle(subtitle: SubtitleData) {
    try {
      const data = await this.getStorageData();
      
      // 添加新字幕
      data.subtitles.push(subtitle);
      
      // 如果超过最大数量，删除最旧的
      if (data.subtitles.length > data.maxSubtitles) {
        data.subtitles = data.subtitles.slice(-data.maxSubtitles);
      }

      await this.setStorageData(data);
    } catch (error) {
      console.error('添加字幕失败:', error);
    }
  }

  public async clearSubtitles() {
    try {
      await this.setStorageData({
        subtitles: [],
        maxSubtitles: SubtitleManager.MAX_SUBTITLES
      });
    } catch (error) {
      console.error('清空字幕失败:', error);
    }
  }
}

// 创建字幕管理器实例
const subtitleManager = new SubtitleManager();

// 监听来自内容脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch (message.type) {
    case 'NEW_SUBTITLE':
      subtitleManager.addSubtitle(message.data);
      break;
    case 'CLEAR_SUBTITLES':
      subtitleManager.clearSubtitles();
      break;
    default:
      console.warn('未知的消息类型:', message.type);
  }
});

// 监听扩展安装或更新
chrome.runtime.onInstalled.addListener(async () => {
  // 初始化存储
  await subtitleManager.clearSubtitles();
  
  // 注册侧边栏
  if (chrome.sidePanel) {
    await chrome.sidePanel.setOptions({
      path: 'sidepanel.html',
      enabled: true
    });
  }
});

// 监听来自 content script 的消息
chrome.runtime.onMessage.addListener((
  request: MessageType,
  _sender: chrome.runtime.MessageSender,
  sendResponse: (response: SubtitleResponseType) => void
) => {
  if (request.type === 'FETCH_SUBTITLE') {
    // 处理跨域请求
    fetch(request.url, {
      headers: {
        'Origin': 'https://www.bilibili.com',
        'Referer': 'https://www.bilibili.com'
      }
    })
    .then(response => response.json())
    .then(data => {
      sendResponse({ success: true, data });
    })
    .catch(error => {
      sendResponse({ success: false, error: error.message });
    });
    return true; // 保持消息通道开放
  }

  if (request.type === 'SUBTITLE_UPDATE') {
    // 转发字幕更新到侧边栏
    chrome.runtime.sendMessage({
      type: 'SUBTITLE_UPDATE',
      subtitle: request.subtitle
    });
  }
});

// 监听扩展图标点击
chrome.action.onClicked.addListener((tab) => {
  if (chrome.sidePanel) {
    // 打开侧边栏
    chrome.sidePanel.open({ windowId: tab.windowId });
  }
}); 